/**
 * The main window of the logic circuit simulator application.
 * 
 * @author Giuseppe Mendola (giuseppe.mendola@usi.ch);Gregory Banfi (gregory.banfi@usi.ch);
 */

package ch.usi.inf.pf2.gui;

import javax.swing.JFrame;
import java.awt.Dimension;
import java.awt.Scrollbar;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JToggleButton;
import javax.swing.KeyStroke;

import java.awt.BorderLayout;
import java.io.File;

import javax.swing.ButtonGroup;

import ch.usi.inf.pf2.Component;
import ch.usi.inf.pf2.ReadCircuit;
import ch.usi.inf.pf2.WriteCircuit;

public final class DrawingFrame extends JFrame {

	private final JMenuItem save;
	private final JMenuItem open;
	private final JFileChooser chooser;
	private final JButton openButton;
	private final JButton saveButton;

	final int SHORTCUT_MASK = Toolkit.getDefaultToolkit()
			.getMenuShortcutKeyMask();

	private void quit() {
		System.exit(0);
	}

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private final Model model;

	/**
	 * This method returns the model field of DrawingFrame
	 * 
	 * @return model A model
	 */
	public Model getModel() {
		return model;
	}

	public DrawingFrame(final Model model) {
		setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
		this.model = model;
		setTitle("CircSim - Circuit Simulator-Staitic");
		setSize(new Dimension(800, 600));
		save = new JMenuItem("Save");
		open = new JMenuItem("Open");
		openButton = new JButton(
				new ImageIcon(
						"/Users/giuseppe/Documents/workspace/circsim-circuit-simulator/bin/ch/usi/inf/pf2/gui/openIcon.png"));
		saveButton = new JButton(
				new ImageIcon(
						"/Users/giuseppe/Documents/workspace/circsim-circuit-simulator/bin/ch/usi/inf/pf2/gui/saveIcon.png"));

		chooser = new JFileChooser();

		final JMenuBar menuBar = new JMenuBar();
		final JMenu editMenu = new JMenu("Edit");
		final JMenu fileMenu = new JMenu("File");
		editMenu.add(new SelectAllAction(model));
		editMenu.add(new DeleteAction(model));
		fileMenu.add(open);
		open.setAccelerator(KeyStroke
				.getKeyStroke(KeyEvent.VK_O, SHORTCUT_MASK));

		open.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {

				int returnVal = chooser.showOpenDialog(open);
				if (returnVal == JFileChooser.APPROVE_OPTION) {
					System.out.println("You chose to open this file: "
							+ chooser.getSelectedFile().getName());
				}
				File openingFile = chooser.getSelectedFile();
				String path = openingFile.getPath();
				ReadCircuit reader = new ReadCircuit(path);

				for (Component c : reader.components)
					Model.getDrawing().add(c);

			}
		});
		fileMenu.add(save);
		save.setAccelerator(KeyStroke
				.getKeyStroke(KeyEvent.VK_S, SHORTCUT_MASK));
		save.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {

				int returnVal = chooser.showSaveDialog(save);
				if (returnVal == JFileChooser.APPROVE_OPTION) {
					System.out.println("You chose to save this file: "
							+ chooser.getSelectedFile().getName());
				}

				File savedFile = chooser.getSelectedFile();
				String path = savedFile.getPath();
				WriteCircuit writer = new WriteCircuit(Drawing.getComponents(),
						path);
			}
		});

		fileMenu.addSeparator();

		/**
		 * Quit function: quit the application.
		 */
		JMenuItem close = new JMenuItem("Close");
		close.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,
				SHORTCUT_MASK));
		close.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				quit();
			}
		});
		fileMenu.add(close);

		menuBar.add(fileMenu);
		menuBar.add(editMenu);
		setJMenuBar(menuBar);

		final JPanel upperPanel = new JPanel();
		upperPanel.add(openButton);
		openButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				int returnVal = chooser.showOpenDialog(open);
				if (returnVal == JFileChooser.APPROVE_OPTION) {
					System.out.println("You chose to open this file: "
							+ chooser.getSelectedFile().getName());
				}
				File openingFile = chooser.getSelectedFile();
				String path = openingFile.getPath();
				ReadCircuit reader = new ReadCircuit(path);

				for (Component c : reader.components)
					Model.getDrawing().add(c);

			}
		});
		upperPanel.add(saveButton);
		saveButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				int returnVal = chooser.showSaveDialog(save);
				if (returnVal == JFileChooser.APPROVE_OPTION) {
					System.out.println("You chose to save this file: "
							+ chooser.getSelectedFile().getName());
				}

				File savedFile = chooser.getSelectedFile();
				String path = savedFile.getPath();
				WriteCircuit writer = new WriteCircuit(Drawing.getComponents(),
						path);
			}
		});
		JButton changeValueButton1 = new JButton("Set Input Value 1");
		upperPanel.add(changeValueButton1);
		changeValueButton1.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				Drawing.changeValue1();
			}
		});
		JButton changeValueButton0 = new JButton("Set Input Value 0");
		upperPanel.add(changeValueButton0);
		changeValueButton0.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				Drawing.changeValue0();
			}
		});
		JButton runButton = new JButton("Run the Circuit");
		upperPanel.add(runButton);
		runButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if (Drawing.isMultipleInput()){
				Drawing.run();}
			}
		});
		add(upperPanel, BorderLayout.NORTH);

		final DrawingArea drawingArea = new DrawingArea(model);
		Scrollbar scrollbar = new Scrollbar(0);
		drawingArea.add(scrollbar);

		final JToolBar toolBar = new JToolBar(1);
		add(toolBar, BorderLayout.WEST);

		// create tool buttons
		final ButtonGroup group = new ButtonGroup();
		boolean first = true;
		for (final Tool tool : drawingArea.getTools()) {
			final JToggleButton button = new JToggleButton();
			button.setSize(90, 10);
			button.setText(tool.getName());
			button.setToolTipText(tool.getName());
			button.setIcon(tool.getIcon());
			toolBar.add(button);
			group.add(button);
			if (first) {
				button.setSelected(true);
				first = false;
			}
			button.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(final ActionEvent ev) {
					drawingArea.setCurrentTool(tool);
				}
			});
		}
		toolBar.addSeparator();

		JButton selectAll = new JButton(new SelectAllAction(model));
		JButton delete = new JButton(new DeleteAction(model));

		toolBar.add(selectAll);
		toolBar.add(delete);

		add(drawingArea, BorderLayout.CENTER);

		final StatusBar statusBar = new StatusBar(model);
		add(statusBar, BorderLayout.SOUTH);
		pack();

		// register listeners
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(final WindowEvent ev) {
				// TODO: Open a dialog to as the user whether they really want
				// to quit
				ImageIcon icono = new ImageIcon("");
				int res = JOptionPane.showConfirmDialog(upperPanel, "Exit Circsim", "Confirm Exit", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, icono);
				if(res == JOptionPane.YES_OPTION)
				quit();
				
			}
		});
	}
}
